#include <cstdio>
#include <string>
#include <pthread.h>
#include <unistd.h>
#include <functional>
using namespace std;
namespace jlf
{
    static uint32_t number = 1;

    class thread
    {
        using func_t = function<void()>;

    private:
        void EnAbleRunning()
        {
            _is_running = 1;
        }
       
        static void *routine(void *args)
        {
            thread *self = (thread *)args;
            self->EnAbleRunning();
            self->Detach();
            pthread_setname_np(self->_tid, self->_name.c_str());
            self->_func();
            return nullptr;
        }

    public:
        thread(func_t func)
            : _tid(0),
              _is_deatch(0),
              _is_running(0),
              _res(nullptr),
              _func(func)
        {
            _name = "thread-" + to_string(number++);
        }
        void Start()
        {
            if (_is_running)
                return;
            int n = pthread_create(&_tid, nullptr, routine, this);
            if (n != 0)
            {
                perror("Pthread_create");
                return;
            }
            else
            {
                printf("new thread was created successfully\n");
            }
        }
        void Stop()
        {
            if (_is_running)
            {
                int n = pthread_cancel(_tid);
                if (n != 0)
                {
                    perror("pthread_cancel");
                    return;
                }
                else
                {
                    printf("线程被取消\n");
                }
                _is_running = 1;
            }
        }
        void EnAbleDetach()
        {
            _is_deatch = 1;
        }
        void Detach()
        {
            if (_is_deatch)
            {
                printf("线程被分离了\n");
                pthread_detach(_tid);
            }
        }
        void Join()
        {
            if(_is_deatch)
            {
                printf("线程被分离了,无法join\n");
                return;
            }
            printf("线程被join了\n");
            pthread_join(_tid, &_res);
        }
        ~thread()
        {
        }

    private:
        pthread_t _tid;
        string _name;
        int _is_deatch;
        int _is_running;
        void *_res;
        func_t _func;
    };
}